<?php

namespace App\Jobs\Article;

use App\Service\Article\ArticleOperateService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ArticleOperate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    const QUEUE_NAME = '{tiger-articleOperate}';

    public $timeout = 1800;


    private array $data;

    /**
     * 文章-异步操作(点赞、分享、收藏)
     *
     * @param array $data
     */
    public function __construct(array $data)
    {
        $this->data = $data;//参数
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info("articleOperateJobsStart:", ['data' => $this->data]);
        $articleId  = $this->data['articleId'] ?? 0;  // 单个文章id
        $articleIds = $this->data['articleIds'] ?? [];// 多个文章id
        if ($articleIds) {
            foreach ($articleIds as $id) {
                self::operate($this->data['type'], $id, $this->data['userId']);
            }
        } elseif ($articleId) {
            self::operate($this->data['type'], $articleId, $this->data['userId']);
        }
    }

    public static function operate(int $type, int $articleId, int $userId)
    {
        try {
            ArticleOperateService::operate($type, $articleId, $userId);
        } catch (\Exception $e) {
            Log::error(
                'articleOperateErr', [
                    'type'      => $type,
                    'articleId' => $articleId,
                    'userId'    => $userId,
                    'msg'       => $e->getMessage(),
                ]
            );
        }
    }
}
